#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2019/2/14
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :TX14_PastOneYearsAvgIncomeTaxAmt
# @Software  :PyCharm


import json
import re
import sys
import datetime
import pandas as pd
import math
from dateutil.relativedelta import relativedelta

'''eof
name:近一年月均所得税应纳税额
code:TX14_PastOneYearsAvgIncomeTaxAmt
tableName:
columnName:
groups:税务模块-税务
dependencies:TX_CQ_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


# reload(sys)
# sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def inquireIsReportNo(data):
    """
    判断是否存在reportNo
    :param data:
    :return:True/False
    """
    try:

        is_reportNo = True if len(data.get("reportNo")) > 0 else False

    except:
        is_reportNo = False

    return is_reportNo


def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        ic_data = TX_CQ_DSJ["data"].get(table_Name)
        return ic_data if isinstance(ic_data, list) and len(ic_data) > 0 else [{}]

    except:
        return [{}]

def isfloat(x):
    '''
    判断x为float类型
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float):
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True', 'NAN', 'nan',
                     'False', '-inf', '-INF', '-INFINITY', '-infinity', 'NaN', 'Nan']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def formatDate(time):

    import re
    import datetime
    try:
        r = re.compile(r'\D')
        tmp = r.sub('', time)
        if tmp.isdigit():
            date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
            return date
        else:
            return None
    except:
        return None

def dataPre(dataList=None, key=None):
    """
    对list里面的列表去重月份不标准的
    :param dataList:
    :param key:
    :return:
    """
    dataListTemp = dataList
    data = []
    for i in range(len(dataListTemp)):
        temp = dataListTemp[i].get(key)
        try:
            temp = int(temp)
        except:
            temp = None
            pass

        if temp:
            data.append(dataListTemp[i])
        else:
            pass

    if len(data) == 0:
        data = [{}]
    else:
        pass

    return data

def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """
    data_value = str(data_value)
    return_data = None
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data


def incomeTaxDataMerge(syptQysdsNd, syptQysdsA1, putBackYear=2, CcrDate=None):
    """
    所得税纳税数据拆分为近2年的月度数据

    :param syptQysdsNd: 年度汇算清缴表，类型[{}]
    :param syptQysdsA1: A1表，类型[{}]
    :param putBackYear: 回推时间，默认为2年
    :param CcrDate: 测试时间，默认为None，格式为datetime.date(2019, 2, 19)；
    :return: IncomeTaxData为Series
    """
    # 字典排序
    syptQysdsA1 = dataPre(syptQysdsA1, key='YF')
    syptQysdsA1 = sorted(syptQysdsA1, key=lambda x: int(x['YF']) if x.has_key('YF') else None)
    # 生成时间轴
    dateIndexList = []
    # 用于生产
    if CcrDate is None:
        CcrYearMonth = datetime.datetime.now().strftime('%Y-%m-%d')[:7]
        CcrDate = CcrYearMonth + '-01'
        StartDateTmp = str(datetime.datetime.now().year - putBackYear) + CcrDate[4:]
        StartDate = StartDateTmp[:7] + '-01'
    else:
        CcrYear = datetime.datetime.strptime(convertDataType(CcrDate, 'date_time'), '%Y-%m-%d').date().year
        CcrDate = convertDataType(CcrDate, 'date_time')[:7] + '-01'
        StartDate = str(CcrYear - putBackYear) + convertDataType(CcrDate, 'date_time')[4:]

    dateSet = pd.date_range(StartDate, CcrDate, freq='M')

    for i in dateSet:
        year = i.date().year
        month = i.date().month
        dateIndexList.append(str(year) + str(month))

    IncomeTaxData = pd.Series('None', index=dateIndexList)

    if syptQysdsA1 == [{}]:
        return IncomeTaxData
    else:
        # 使用A1表(默认为只有按季度缴纳)
        if syptQysdsA1 != [{}]:
            for i in range(len(syptQysdsA1)):
                # ND = convertDataType(syptQysdsA1[i].get('ND'), 'int')
                # YF = convertDataType(syptQysdsA1[i].get('YF'), 'int')
                QSRQ = syptQysdsA1[i].get('skssqq')
                QZRQ = syptQysdsA1[i].get('skssqz')
                # QSRQ = QSRQ[:7]
                # QZRQ = QZRQ[:7]
                if QSRQ in null_type_list or QZRQ in null_type_list or formatDate(QSRQ) == None or formatDate(QZRQ) == None:
                    pass
                else:
                    YNSSDE = convertDataType(syptQysdsA1[i].get('YNSSDE'), 'float')
                    # QSNY = str(QSRQ[:4])+str(QSRQ[5:7])
                    # QZNY = str(QZRQ[:4])+str(QZRQ[5:7])
                    Mons = (int(QZRQ[:4])-int(QSRQ[:4]))*12 + (int(QZRQ[5:7])-int(QSRQ[5:7]))
                    if(Mons>=0):
                        if YNSSDE in null_type_list:
                            pass
                        else:
                            ND = QZRQ[:4]
                            YF = QZRQ[5:7]
                            YNSSDE_Ave = round(float(YNSSDE)/(Mons+1),2)
                            for j in range(Mons+1):
                                NDYF = datetime.datetime.strptime(QZRQ,'%Y-%m-%d') - relativedelta(months=j)
                                ND = int(str(NDYF)[:4])
                                YF = int(str(NDYF)[5:7])
                                key = str(ND) + str(YF)
                                if key in IncomeTaxData.index:
                                    IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE_Ave
                                else:
                                    pass
                    else:
                        pass
        return IncomeTaxData



def countdownOneYearsTaxAmtQuarterCheck(spDate=None):
    """
    计算企业前一年纳税金额，求得纳税金额小于配置的金额则拒绝，大于等于配置的金额则通过
    （年均纳税额=增值税年平均额+所得税年平均额）。其中计算方法：
    （1）计算增值税前一年纳税额，加总月份区间为申请月份-1到申请月份-12的纳税额
    （2）计算所得税前一年纳税额
    只有季度纳税A1表，加总月份区间为申请月份-1到申请月份-12的纳税额。

    :return:
    """
    syptQysdsNd = [{}]
    syptQysdsA1 = formatData('syptQysdsA1')

    # 所得税数据合并
    if syptQysdsA1 == [{}]:
        return u'缺失值'
    else:
        incomeDataSeries = incomeTaxDataMerge(syptQysdsNd=syptQysdsNd, syptQysdsA1=syptQysdsA1, CcrDate=spDate)
        if isfloat(incomeDataSeries[23]):
            incomeDataSeries[incomeDataSeries == 'None'] = 0
            lastOneIncomeSum = sum(incomeDataSeries[12:24])
        elif isfloat(incomeDataSeries[23])==False and isfloat(incomeDataSeries[22]):
            incomeDataSeries[incomeDataSeries == 'None'] = 0
            lastOneIncomeSum = sum(incomeDataSeries[11:23])
        elif isfloat(incomeDataSeries[23])==False and isfloat(incomeDataSeries[22])==False and isfloat(incomeDataSeries[21]):
            incomeDataSeries[incomeDataSeries == 'None'] = 0
            lastOneIncomeSum = sum(incomeDataSeries[10:22])
        else:
            incomeDataSeries[incomeDataSeries == 'None'] = 0
            lastOneIncomeSum = sum(incomeDataSeries[9:21])
    return round(lastOneIncomeSum/12, 4)


result = countdownOneYearsTaxAmtQuarterCheck()

# try:
#     if __name__ == '__main__':
#         # 下面添加需要执行的函数
#         # 读取json文件
#         file_obj = open(r'G:\\BBDWork\\project\\modelMigration\\data\\TX_CQ_DSJ.js', 'r')
#         content = file_obj.read()
#         TX_CQ_DSJ = json.loads(content, strict=False)['TX_CQ_DSJ']
#
#         # 审批时间
#         spDateTime = '20190312'
#
#         # 连续性纳税校验
#         aa = countdownOneYearsTaxAmtQuarterCheck()
#         # aa = countdownOneYearsTaxAmtQuarterCheck(spDate=spDateTime)
#         pass
# except Exception as e:
#     print('exception happen')
#     raise e